﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MaxLeaf.Common;
using MaxLeaf.DB;
using System.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

namespace MaxLeaf.DAL.W2K
{
    /*
             * 
             * declare @p2 int
set @p2=1
exec GetICMaxNum 't_BarCodeHeader',@p2 output
print @p2
             * 
             * DECLARE @TmpID INT 
DECLARE @fprojectval varchar(80) 
select  @fprojectval='' 
SET @TmpID = (SELECT FID FROM t_BillCodeRule WITH(READUNCOMMITTED) WHERE fbilltypeid='1014003' and fprojectid=3)
update t_billcoderule set fprojectval = fprojectval+1,@fprojectval=isnull(fprojectval,1),flength=case when (flength-len(fprojectval)) >= 0 then flength else len(fprojectval) end where FID = @TmpID 
Update ICBillNo Set FCurNo = @fprojectval where fbillid = 1014003
             * 
             * Update ICBillNo Set FDesc = '00000009' Where FBillID = '1014003'
             * 
             * 
             * select * from t_BarCodeHeader
SELECT * FROM ICBillNo WHERE FBillID = 1014003
select top 1 FBillID from t_BarCode where FItemID=319
             * 
              UPDATE t_ICItem SET FGoodsBarCode = '23456789', 
            FSalePrice = 0, 
            FVIPPrice = 0, 
            FSilverVIPPrice = 0, 
            FGoldVIPPrice = 0  
   WHERE FItemID = 319
             */


    public class goods_barcodeDAL : BaseDAL
    {
        public goods_barcodeDAL()
            : base()
        {
            strK3TableName = "t_BarCode";
            strWebTableName = "goods_barcode";

            strK3MapKeyFieldName = "FID";
            strWebMapKeyFieldName = "barcode_id";
            strWebMapKeyTableName = "k3_goods_barcode";

            mblnIsIdentity = true;

            //strK3DestRealKeyFieldName = "FBarCode";
            //strWebOrgDestRealKeyFieldName = "barcode";

            mblnNeedEditKeyValue = false;

            strFieldNames = "FItemID,FBillID,FIndex,FCodeType,FBarCode,FUnitID,FTypeID";

            strFItemClassID = null;
        }

        protected override void Update_Before(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drData)
        {
        }
        public override int Update(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, string strKeyValue)
        {
            KeyValuePair<string,IDataParameter[]> kvp=dbOrgWebReadCon.CreateCondParam(new Dictionary<string,object>(){{"barcode_id",strKeyValue}});
            DataRow drOrg = dbOrgWebReadCon.GetDataFirstRow(string.Format("select goods_id from goods_barcode where {0}", kvp.Key), kvp.Value);
            if (drOrg == null) throw new MaxLeafException(string.Format("goods_barcode not exist  {0}",strKeyValue));
            dictOtherKeyFieldsCond = new Dictionary<string, object>() { { "goods_id", drOrg["goods_id"] } };
            dictDestOtherKeyFieldsCond = new Dictionary<string, object>() { { "fitemid",new goods_mainDAL().GetDestMapKeyValue(dbOrgWebReadCon,dbOrgWebWriteCon,dbDestK3Con,CvtFunc.ToString( drOrg["goods_id"])) } };
            
            int iDestKey= base.Update(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con,   strKeyValue);
            

            return iDestKey;
        }


        protected override void DAL_GetFieldData(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, string strK3FieldName, DataRow drOrgData, DataRow drDestData)
        {
            
            if (strK3FieldName.Equals("FitemID", StringComparison.InvariantCultureIgnoreCase))
            {
                 if(CvtFunc.ToString(drDestData[strK3FieldName]).Length==0)
                {
                    drDestData[strK3FieldName] = CvtFunc.ToString(new goods_mainDAL().GetDestMapKeyValue(dbOrgWebReadCon,dbOrgWebWriteCon, dbDestK3Con, CvtFunc.ToString(drOrgData["goods_id"])));
                 }

            }
            else if (strK3FieldName.Equals("FBillID", StringComparison.InvariantCultureIgnoreCase))
            {

                if(CvtFunc.ToString(drDestData[strK3FieldName]).Length==0)
                {
                    drDestData[strK3FieldName] = GetFBillID(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestK3Con, drOrgData, drDestData);
                }
                
                
            }
            else if (strK3FieldName.Equals("FIndex", StringComparison.InvariantCultureIgnoreCase))
            {
                if(CvtFunc.ToInt(drDestData[strK3FieldName])==0)
                {
                    drDestData[strK3FieldName] = GetFIndex(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestK3Con, drOrgData, drDestData);
                }
            }
            else if (strK3FieldName.Equals("FCodeType", StringComparison.InvariantCultureIgnoreCase))
            {
                if(CvtFunc.ToInt(drDestData["FID"])==0)
                {
                    drDestData[strK3FieldName] = GetFCodeType(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestK3Con, drOrgData, drDestData);
                }
            }
                else if (strK3FieldName.Equals("FBarCode", StringComparison.InvariantCultureIgnoreCase))
            {
               
                    drDestData[strK3FieldName] =  drOrgData["barcode"];
                
            }
               else if (strK3FieldName.Equals("FUnitID", StringComparison.InvariantCultureIgnoreCase))
            {

                if (dbDestK3Con.GetDataFirstRow("select FMeasureUnitID from t_MeasureUnit where FMeasureUnitID=@FMeasureUnitID", new SqlParameter[] { new SqlParameter("@FMeasureUnitID", drOrgData["measure_unit_id"]) }) != null)
                {
                    drDestData[strK3FieldName] = drOrgData["measure_unit_id"];
                }
                else
                {
                    throw new MaxLeafException(string.Format("K3不存在 measure_unit_id {0} ", drOrgData["measure_unit_id"]));
                }
                
            }
            else if (strK3FieldName.Equals("FTypeID", StringComparison.InvariantCultureIgnoreCase))
            {
               
                    drDestData[strK3FieldName] = 4;
                
            }
            else
            {
                drDestData[strK3FieldName] = 0;
            }            
        }

        private string GetFCodeType(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            string strSql = "select FCodeType from t_barcode where  FBillID=@FBillID and FCodeType=0";
            if (dbDestK3Con.GetDataFirstRow(strSql
                    , dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "FBillID", drDestData["FBillID"] } }).Value
                ) != null)
            {
                return "1";
            }
            return "0";
        }

        private string GetFIndex(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            string strSql = "select max(FIndex) from t_barcode where  FBillID=@FBillID";
            int iMax = CvtFunc.ToInt(dbDestK3Con.GetValue(strSql
                    , dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { { "FBillID", drDestData["FBillID"] } }).Value
                )) + 1;

            return CvtFunc.ToString(iMax);
        }

        private string GetFBillID(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestK3Con, DataRow drOrgData, DataRow drDestData)
        {
            string strFBillID = dbDestK3Con.GetValue("select top 1 FBillID from t_barcode where fitemid=@fitemid"
                , new SqlParameter[] { new SqlParameter("@fitemid", drDestData["fitemid"] ) });
            
            if(strFBillID.Length>0)return strFBillID;

            string strSql = @"DECLARE @TmpID INT 
                DECLARE @fprojectval varchar(80) 
                select  @fprojectval='' 
                SET @TmpID = (SELECT FID FROM t_BillCodeRule WITH(READUNCOMMITTED) WHERE fbilltypeid='1014003' and fprojectid=3)
                update t_billcoderule set fprojectval = fprojectval+1,@fprojectval=isnull(fprojectval,1),flength=case when (flength-len(fprojectval)) >= 0 then flength else len(fprojectval) end where FID = @TmpID 
                Update ICBillNo Set FCurNo = @fprojectval where fbillid = 1014003";
            dbDestK3Con.ExecuteSql(strSql);

            strSql = "select FCurNo from ICBillNo  where fbillid = 1014003";
            string strFCurNo = dbDestK3Con.GetValue(strSql);

            strSql = "update ICBillNo Set FDesc = @FDesc Where FBillID = '1014003'";
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { new SqlParameter("@FDesc",BaseFunctions.FormatWithZero(CvtFunc.ToString(  CvtFunc.ToInt(strFCurNo)+1 ),8) ) });

            strSql = "exec GetICMaxNum 't_BarCodeHeader',@p2 output";
            SqlParameter p2 = new SqlParameter("@p2", SqlDbType.Int);
            p2.Direction = ParameterDirection.Output;
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { p2 });

            if (CvtFunc.ToInt( p2.Value) <= 0)
            {
                throw new MaxLeafException(string.Format("GetICMaxNum {0}", p2.Value)); 
            }
            strFBillID =CvtFunc.ToString( p2.Value);
            
            BaseFunctions.FormatWithZero(strFCurNo, 8);

            strSql = @"insert into t_barcodeheader(FBillID,fclasstypeid,FbillNo) values(@FBillID,@fclasstypeid,@FbillNo)";
            dbDestK3Con.ExecuteSql(strSql, new SqlParameter[] { 
                new SqlParameter("@FBillID", strFBillID) 
                ,new SqlParameter("@fclasstypeid", "1014003") 
                ,new SqlParameter("@FbillNo", BaseFunctions.FormatWithZero(strFCurNo, 8)) 
            });

            return strFBillID;

        }
                

        protected override void WriteK3Log(DBAccess dbDestK3Con, int intKeyValue)
        {
             string strSql = @"insert into mLog(logtype,keyvalue,logstatus)
                values(@logtype,@keyvalue,@logstatus)";
             dbDestK3Con.ExecuteSql(strSql, dbDestK3Con.CreateCondParam(new Dictionary<string, object>() { 
                 {"logtype",LogType.goods_barcode.ToString()}
                 ,{"keyvalue",intKeyValue.ToString()}
                 ,{"logstatus","1"}
             }).Value);
            
        }
        
    }
}